var rootPath = getRootPath();

$(function() {
	jQuery.validator.addMethod("checkRleName", function(value, element) {
		var oriRleName = $("#oriRleName").val();
		return checkRleName(value,oriRleName);
	}, "角色名称已存在");
	
	$("#roleEditForm").validate({
		rules : {
			rleName :  {
				required : true,
				maxlength:50,
				checkRleName : true
			}
		},
		onkeyup:false,
		focusCleanup:true,
		success:"valid",
		submitHandler:function(form){
			var jsonObject = JSON.parse(JSON.stringify($('#roleEditForm').serializeJson()));
			var json;
			if(jsonObject.resIds == null) {
				jsonObject.resIds = [];
				json = JSON.stringify(jsonObject);
			} else {
				json = JSON.stringify($('#roleEditForm').serializeJson());
			}
			$.ajax({
				url: rootPath + '/role/updateRoleRes',
		        type: 'POST',
		        data : json,
	            contentType: 'application/json;charset=UTF-8', 
		        success: function (data) {
					if(data.returnCode == "0000") {						
						layer.msg('成功更新权限!',{icon:1,time:1000},function() {						
							parent.window.location.href = rootPath + '/rolePage';
							var index = parent.layer.getFrameIndex(window.name);
							parent.layer.close(index);
						});
					} else {
						layer.alert(data.returnMessage);
					}
		        },
		        error: function (jqXHR, textStatus, errorThrown) {
		        	layer.alert("更新权限失败:(");
		        }
		    });
		}
	});
});

function checkRleName(rleName,oriRleName) {
	var isValidRleName = true;
	if(rleName != oriRleName) {
		$.ajax({
			url: rootPath + '/role/checkRleName',
	        type: 'GET',
	        async: false,
	        data: {
	        	"rleName" : rleName
	        },
	        success: function (data) {
	        	if(data != "true") {
	        		isValidRleName = false;
	        	}
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	        	layer.alert("error:(");
	        }
	    });
	}
	return isValidRleName;
}